from django.shortcuts import render,HttpResponse,redirect,reverse
from user.models import User

# Create your views here.
def index_handler(request):
    # 判断session中是否有user
    if 'user' in request.session.keys():
        user = request.session['user']
        context = {'login_user':user}
    else:
        context = {}
    print(context)
    return render(request,'index.html',context=context)


def login_handler(request):
    # 如果是Get请求，返回登录页
    if request.method == 'GET':
        return render(request,'login.html')
    # 如果是Post请求，处理登录数据
    else:
        # 得到表单提交的用户名与密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 查询，返回QuerySet
        users = User.objects.filter(username=username,password=password)
        # 如果符合的结果，表示账号与密码正确
        if users:
            user = users[0]
            # 添加用户信息到session中的user键中，重定向回首页
            request.session['user'] = {'id':user.id,'username':user.username}
            print(request.session)
            return redirect(reverse('index'))

        # 如果没有结果，表示账号与密码不正确，继续返回登录页，并做提示
        else:
            return render(request,'login.html',context={'message':'账号或密码错误'})


def logout_handler(request):
    del request.session['user']
    return render(request,'index.html')


